    <%--
  Created by IntelliJ IDEA.
  User: 14376
  Date: 2025/3/24
  Time: 08:34
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>忘记密码</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <style>
        body {
            background-color: #f8f9fa;
        }
        .form-container {
            max-width: 400px;
            margin: 50px auto;
            padding: 20px;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        #liveAlertPlaceholder {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 9999;
            width: 100%;
            max-width: 400px;
        }

        #passwordMismatch {
            color: red;
            display: none;
        }

        #EmailOrPhoneMismatch {
            color: red;
            display: none;
        }
    </style>
</head>
<body>
<div id="liveAlertPlaceholder" class="container text-center col-3"></div>
<div class="container">
    <div class="form-container">
        <h2 class="text-center mb-4">忘记密码</h2>
        <form id="resetPasswordForm">
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" class="form-control" id="username" placeholder="请输入用户名" required>
                <small id="usernameHelp" class="form-text text-danger"></small>
            </div>
            <div class="form-group">
                <label for="contactInfo">手机号或邮箱</label>
                <input type="text" class="form-control" id="contactInfo" placeholder="请输入手机号或邮箱" required>
                <div id="EmailOrPhoneMismatch">邮箱或电话号格式错误</div>
                <small id="contactInfoHelp" class="form-text text-danger"></small>
            </div>
            <div class="form-group">
                <label for="password">新密码</label>
                <input type="password" class="form-control" id="password" placeholder="请输入新密码" required>
                <small id="newPasswordHelp" class="form-text text-danger"></small>
            </div>
            <div class="form-group">
                <label for="confirmPassword">确认新密码</label>
                <input type="password" class="form-control" id="confirmPassword" placeholder="请再次输入新密码" required>
                <div id="passwordMismatch">两次输入的密码不一致</div>
                <small id="confirmNewPasswordHelp" class="form-text text-danger"></small>
            </div>
            <div class="form-group">
                <label for="captcha">验证码</label>
                <div class="d-flex">
                    <input type="text" class="form-control mr-2" id="captcha" placeholder="请输入验证码" required>
                    <button type="button" class="btn btn-secondary" id="Vcode">刷新验证码</button>
                </div>
                <small id="captchaHelp" class="form-text text-danger"></small>
            </div>
            <button type="button" class="btn btn-primary w-100" id="ResetPassword">重置密码</button>
            <p class="mt-3 text-center">
                记得密码了？<a href="login.jsp">立即登录</a>
            </p>
        </form>
    </div>
</div>

<!-- jQuery and Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="API.js"></script>
<script src="tools.js"></script>
<script src="bootstrap5/bootstrap.min.js"></script>
<script>
    const vc=document.getElementById("Vcode");
    vc.addEventListener("click",getVcode);
    let Vcode;
    let username;
    let password;
    let confirmPassword;
    let UserVcode;
    let contactInfo;

    // 动态监测username和password的变化
    $(document).ready(function () {
        // 监听username输入框的变化
        $('#username').on('input', function () {
            username = $(this).val();
            console.log('当前用户名:', username); // 可选：调试用
        });

        // 监听password输入框的变化
        $('#password').on('input', function () {
            password = $(this).val();
            console.log('当前密码:', password); // 可选：调试用
        });

        $('#confirmPassword').on('input', function () {
            confirmPassword = $(this).val();
            console.log('当前密码:', confirmPassword); // 可选：调试用
        });


        //监听captcha输入框的变化
        $('#captcha').on('input', function () {
            UserVcode = $(this).val();
            console.log('当前密码:', UserVcode); // 可选：调试用
        });
        $('#contactInfo').on('input', function () {
            contactInfo = $(this).val();
            console.log('当前密码:', contactInfo);// 可选：调试用
        });
        $('#confirmPassword').on('blur', function () {
            if (password && confirmPassword) {
                if (password !== confirmPassword) {
                    $('#passwordMismatch').show();
                } else {
                    $('#passwordMismatch').hide();
                }
            } else {
                $('#passwordMismatch').hide();
            }
        });
        $('#contactInfo').on('blur', function () {
            const s = validateEmailOrPhone(contactInfo);
            console.log(s.isValid)
            if (contactInfo) {
                if (s.isValid) {
                    $('#EmailOrPhoneMismatch').hide();
                } else {
                    $('#EmailOrPhoneMismatch').show();
                }
            } else {
                $('#EmailOrPhoneMismatch').hide();
            }
        });
    });


    const RP = document.getElementById("ResetPassword");
    RP.addEventListener("click", async function () {
        if (username == null || password == null) {
            appendAlert("请输入用户名和密码")
            return;
        }
        if (password != confirmPassword) {
            appendAlert("两次密码输入不一致");
            return;
        }
        if (contactInfo == null) {
            appendAlert("请输入手机号或邮箱")
        }
        if (validateEmailOrPhone(contactInfo).isValid == false) {
            appendAlert("邮箱或电话号格式错误")
        }
        if (Vcode == null) {
            appendAlert("请输获取验证码")
            return;
        }
        try{
            const RPCode=await ResetPassword(username,password,contactInfo);
            if (Vcode != UserVcode) {
                appendAlert("验证码错误")
            } else {
                if (RPCode == 200) {
                    appendAlert("密码重置成功")
                    window.location.href = "login.jsp";
                } else if (RPCode == 401) {
                    appendAlert("用户名不存在请重新输入");
                } else if(RPCode==402){
                    appendAlert("输入的邮件或手机号有误");
                }else if (RPCode==403){
                    appendAlert("请求失败");
                }
            }
        }catch (error){
            console.error(error);
        }
    });

    function ResetPassword(username,password,contactInfo){
        // 返回一个Promise对象
        return new Promise((resolve, reject) => {
            // 使用ajax发送POST请求
            $.ajax({
                url: '/demo1_war_exploded/API/resetPassword', // 请求的URL
                type:'POST', // 请求类型
                dataType: 'json', // 返回的数据类型
                data: {
                    username: username, // 用户名
                    password: password, // 密码
                    EmailOrPhone:contactInfo // 联系方式
                },
                success: function (response) {
                    resolve(response.code); // 返回整个timestamp对象
                },
                error: function (xhr) {
                    reject(new Error('请求失败: ' + xhr.statusText)); // 请求失败时，返回错误信息
                }
            });
        });
    }


    const alertPlaceholder = document.getElementById('liveAlertPlaceholder')
    const appendAlert = function (s) {
        // 先清空之前的警告
        alertPlaceholder.innerHTML = '';
        var yu = s
        const wrapper = document.createElement('div')
        wrapper.innerHTML = [
            `<div class="alert alert-danger alert-dismissible fade show" role="alert">`,
            `   <div>` + yu + `</div>`,
            '   <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
            '</div>'
        ].join('')

        alertPlaceholder.append(wrapper)

        // 5秒后自动关闭
        setTimeout(() => {
            // 使用Bootstrap的alert API来关闭，确保动画效果
            const alertNode = wrapper.querySelector('.alert');
            if (alertNode) {
                const bsAlert = new bootstrap.Alert(alertNode);
                bsAlert.close();
            }
        }, 5000);
    }

</script>
</body>
</html>